<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">{{formProperty.title}}屏控系统</div>
    <div class="login-form-sub-title">控制屏幕，使用电脑硬件轻松操控手机</div>
    <a-form
      ref="loginFormRef"
      :model="userInfo"
      class="login-form"
      layout="vertical"
    >
      <a-form-item
        field="username"
        :rules="[{ required: true, message: $t('login.form.userName.errMsg') }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input
          v-model="userInfo.username"
          :placeholder="$t('login.form.userName.placeholder')"
        >
          <template #prefix>
            <icon-user />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
        field="password"
        :rules="[{ required: true, message: $t('login.form.password.errMsg') }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input-password
          v-model="userInfo.password"
          :placeholder="$t('login.form.password.placeholder')"
          allow-clear
        >
          <template #prefix>
            <icon-lock />
          </template>
        </a-input-password>
      </a-form-item>
      <a-space :size="16" direction="vertical">
        <div class="login-form-password-actions">
          <a-checkbox
            checked="rememberPassword"
            :model-value="loginConfig.rememberPassword"
            @change="setRememberPassword as any"
          >
            {{ $t('login.form.rememberPassword') }}
          </a-checkbox>
        </div>
        <a-button type="primary" v-if="formProperty.curOprType === 'login'" @click="handleSubmit('login')" long :loading="loading">
          {{ $t('login.form.login') }}
        </a-button>
        <a-button :type="formProperty.curOprType === 'login'?'text':'primary'" long @click="handleSubmit('register')"  >
          {{ $t('login.form.register') }}
        </a-button>
        <a-button long v-if="formProperty.curOprType === 'register'" @click="handleSubmit('login')" class="login-form-register-btn" >
          返回
        </a-button>
      </a-space>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import { useI18n } from 'vue-i18n';
  import { useStorage } from '@vueuse/core';
  import { useUserStore } from '@/store';
  import useLoading from '@/hooks/loading';
  import { apiRegister, LoginData } from '@/api/user';

  const router = useRouter();
  const { t } = useI18n();
  const { loading, setLoading } = useLoading();
  const userStore = useUserStore();

  const loginFormRef = ref()

  const formProperty = ref({
    title:'登录',
    curOprType: 'login',
  })

  const loginConfig = useStorage('login-config', {
    rememberPassword: true,
    username: 'admin', // 演示默认值
    password: 'admin123', // demo default value
  });
  const userInfo = reactive({
    username: loginConfig.value.username,
    password: loginConfig.value.password,
  });

  const handleSubmit = async (oprType: string) => {
    if (loading.value) return;
    if (formProperty.value.curOprType !== oprType) {
      formProperty.value.curOprType = oprType;
      if (oprType === 'register') {
        formProperty.value.title = '注册';
        userInfo.username = '';
        userInfo.password = '';
      } else {
        formProperty.value.title = '登录';
      }
      return;
    }
    const validateRes = await loginFormRef.value?.validate()
    if (validateRes) {
      return
    }
    setLoading(true);
    if (oprType === 'register') {
      // 注册逻辑
      try{
        await apiRegister(userInfo)
        Message.success(t('注册成功'));
        handleSubmit('login');
      } finally {
        setLoading(false);
      }
    }
    // 登录逻辑
    try {
      await userStore.login(userInfo as LoginData);
      const { redirect, ...othersQuery } = router.currentRoute.value.query;
      router.push({
        name: (redirect as string) || 'Monitor',
        query: {
          ...othersQuery,
        },
      });
      Message.success(t('login.form.login.success'));
      const { rememberPassword } = loginConfig.value;
      const { username, password } = userInfo;
      // 实际生产环境需要进行加密存储。
      // The actual production environment requires encrypted storage.
      loginConfig.value.username = rememberPassword ? username : '';
      loginConfig.value.password = rememberPassword ? password : '';
    } catch (err) {
      Message.error((err as ValidatedError).msg || '登陆失败');
    } finally {
      setLoading(false);
    }
  }
  const setRememberPassword = (value: boolean) => {
    loginConfig.value.rememberPassword = value;
  };
</script>

<style lang="less" scoped>
  .login-form {
    &-wrapper {
      width: 320px;
    }

    &-title {
      color: var(--color-text-1);
      font-weight: 500;
      font-size: 24px;
      line-height: 32px;
    }

    &-sub-title {
      color: var(--color-text-3);
      font-size: 16px;
      line-height: 24px;
    }

    &-error-msg {
      height: 32px;
      color: rgb(var(--red-6));
      line-height: 32px;
    }

    &-password-actions {
      display: flex;
      justify-content: space-between;
    }

    &-register-btn {
      color: var(--color-text-3) !important;
    }
  }
</style>
